package com.jml.装饰模式.五期.异步多渠道群发框架.start;


import com.jml.装饰模式.五期.异步多渠道群发框架.observer.JmlSubject;
import com.jml.装饰模式.五期.异步多渠道群发框架.observer.ObServer;
import com.jml.装饰模式.五期.异步多渠道群发框架.observer.impl.EmailObServer;
import com.jml.装饰模式.五期.异步多渠道群发框架.observer.impl.SMSObServer;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;


@Component
public class StartService implements ApplicationRunner, ApplicationContextAware {
    @Autowired
    private SMSObServer smsObServer;
    @Autowired
    private EmailObServer emailObServer;
    @Autowired
    private JmlSubject jmlSubject;


    private ApplicationContext applicationContext;

    /**
     * 当我们的SpringBoot启动成功的时候，注册我们的SMSObServer
     *
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        /**
         * 自动注册我们观察者
         * 1.使用Spring获取该ObServer下有那些bean对象
         * 2.直接注添加到集合中
         */
        //根据接口类型返回相应的所有bean
        Map<String, ObServer> map = applicationContext.getBeansOfType(ObServer.class);
        for (String key : map.keySet()) {
            ObServer obServer = map.get(key);
            jmlSubject.addObServer(obServer);
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
